#include "data_flood.h"
#include "libpq-fe.h"


#define DF_DBCONN_STRLEN_MAX 1024

THR_LOCAL char temp_conn_str[DF_DBCONN_STRLEN_MAX] = {0};
THR_LOCAL PGconn* g_conn = NULL;

void get_conn_str(void)
{
    char *host = "127.0.0.1";
    char *port = "10010";
    char *user = "postgres";
    char *dbname = "postgres";
    char *password = "";

    if(user_arg.db_name)
        dbname = user_arg.db_name;
    if(user_arg.db_port)
        port = user_arg.db_port;
    if(user_arg.db_user)
        user = user_arg.db_user;
    if(user_arg.db_password)
        password = user_arg.db_password;
    
    sprintf(temp_conn_str, "host=%s port=%s user=%s dbname=%s password=%s ",host, port, user, dbname, password);
    df_debug("%s", temp_conn_str);
}

void doConnect(char* connstr)
{
    PGconn *conn = NULL;

    if(!connstr) {
        get_conn_str();
        connstr = temp_conn_str;
    }

    conn = PQconnectdb(connstr);

    if(!conn)
    {
        df_error("Can not connect :connstr = %s", connstr);
    }

    if(conn && PQstatus(conn) == CONNECTION_BAD)
    {
        char* msg = strdup(PQerrorMessage(conn));
        PQfinish(conn);
        df_error("Can not connect :%s\n", msg);
        free(conn);
        free(msg);
    }

    g_conn = conn;
}

void doDisconnect(void)
{
    if(g_conn) {
        PQfinish(g_conn);
        g_conn = NULL;
    }
}